package cn.pugle.mianshi.thread1To10;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * 这个交接棒的写法, 最后退出两个线程的地方不好写.
 * <p> Created by tzp on 2017/9/6.
 */
@SuppressWarnings({"Duplicates", "AlibabaRemoveCommentedCode"})
public class PrintToTen7 implements Runnable {
    private AtomicInteger count = new AtomicInteger(1);
    SynchronousQueue<AtomicInteger> queue = new SynchronousQueue<>();

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            while (!Thread.interrupted()) {
                try {
                    AtomicInteger ct = queue.take();
                    int i = ct.get();
                    if (i % 2 == 0 && i <= MAX) {
                        System.out.println(Thread.currentThread() + " " + i);
                        i = ct.incrementAndGet();
                    }
                    if (i <= MAX) {
                        queue.put(ct);
                    } else {
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
//            System.out.println(Thread.currentThread() + " end0");
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            while (!Thread.interrupted()) {
                try {
                    AtomicInteger ct = queue.take();
                    int i = ct.get();
                    if (i % 2 == 1 && i <= MAX) {
                        System.out.println(Thread.currentThread() + " " + i);
                        i = ct.incrementAndGet();
                    }
                    if (i <= MAX) {
                        queue.put(ct);
                    } else {
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
//            System.out.println(Thread.currentThread() + " end1");
        });
        thread2.start();

        try {
            queue.put(count);
            thread1.join();
//            thread2.join();
            //这行加到thread1的break前也行, 重点是最后一棒thread1先能到break, 但是2还阻塞在take处
            queue.put(count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen7().run();
    }
}
